package com.juyu.miliao.api.config;

import com.juyu.miliao.common.dataSource.MultipleDataSourceParser;
import com.juyu.miliao.common.dataSource.key.DataSourceKeyEvaluator;
import com.juyu.miliao.common.exception.IllegalParamException;
import com.juyu.miliao.common.exception.InternalServerErrorException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class GlobalDataSourceKeyEvaluator implements DataSourceKeyEvaluator{
	@Resource
	public MultipleDataSourceParser multipleDataSourceParser;

	public String strategy(String strategy, Object param) {
		if("byUserId".equals(strategy)){
			return getDataSourceKeyByUserId(Long.parseLong(param.toString()));
		}else if("byVideoId".equals(strategy)){
			return getDataSourceKeyByUserId(Long.parseLong(param.toString()));
		}else
			throw new InternalServerErrorException("strategy 类型不支持：" + strategy);
	}


	private String getDataSourceKeyByUserId(long param){
        int slot = (int) (param % 100);
        if(slot > multipleDataSourceParser.getSubDataSourceNames("miliao-user").size())
            throw new IllegalParamException("用户id异常");
        return "miliao-user-" + slot;
	}

}
